import storage from 'store'
import { getInfo, logout, getRoutes } from '@/api/login'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
// import { welcome } from '@/utils/util'
import { asyncRouterMap } from '@/config/router.config'

const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    routes: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_ROUTES: (state, info) => {
      state.routes = info
    }
  },

  actions: {
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          console.log(res)
          // if (result.role && result.role.permissions.length > 0) {
          //   const role = result.role
          //   role.permissions = result.role.permissions
          //   role.permissions.map(per => {
          //     if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
          //       const action = per.actionEntitySet.map(action => { return action.action })
          //       per.actionList = action
          //     }
          //   })
          //   role.permissionList = role.permissions.map(permission => { return permission.permissionId })
          //   commit('SET_ROLES', result.role)
          commit('SET_INFO', res.data)
          // } else {
          //   reject(new Error('getInfo: roles must be a non-null array !'))
          // }
          storage.set('userInfo', res.data)
          storage.set('name', res.data.dengLuZhangHao)
          storage.set('avatar', res.data.imageUrl)
          commit('SET_NAME', res.data.dengLuZhangHao)
          commit('SET_AVATAR', res.data.imageUrl)

          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove('Access-Token')
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
        })
      })
    },
    // 添加路由
    addRoutes ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getRoutes().then(response => {
          const result = response.routes || asyncRouterMap
          commit('SET_ROUTES', result)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
